<template>
  <div>
    <avue-crud
      ref="crudRef"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button
          v-if="permission.menu_delete"
          type="danger"
          @click="handleDelete"
          :icon="useRenderIcon(Delete)"
          >批量删除
        </el-button>
      </template>
      <template #menu="{ row }">
        <!-- 管理员可以新增子项 -->
        <!-- v-if="useUserStoreHook().roles?.includes('administrator')" -->
        <el-button
          type="text"
          v-if="permission.menu_add"
          class="ml-3"
          @click.stop="
            () => {
              isAddSon = true;
              handleAdd(row);
            }
          "
        >
          新增子项
        </el-button>
      </template>
    </avue-crud>
  </div>
</template>

<script setup lang="ts">
import type { Ref } from "vue";
import type { ResultType } from "@/api/system/menu";
import type { CudOptions } from "@/hooks/crud/useTableCUD";
import { add, getList, getMenu, remove, update } from "@/api/system/menu";
import Delete from "@iconify-icons/ep/delete";
// hooks
import useTablePage from "@/hooks/crud/useTablePage";
import useTableRequest from "@/hooks/crud/useTableRequest";
import useTableSearch from "@/hooks/crud/useTableSearch";
import useTableSelection from "@/hooks/crud/useTableSelection";
import useTablePermission from "@/hooks/crud/useTablePermission";
import useTableCUD from "@/hooks/crud/useTableCUD";

import { useUserStoreHook } from "@/stores/modules/user";
import { useGlobal } from "@pureadmin/utils";
import { ElMessage, ElMessageBox } from "element-plus";

const { validData } = useGlobal<GlobalPropertiesApi>();

/** CRUD Table */
const crudRef = ref();
const form: Ref<any> = ref({});

const { currentChange, sizeChange, page } = useTablePage();
const { onLoad, data, loading } = useTableRequest<Promise<ResultType>>(
  getList,
  {
    otherFunc: () => {
      crudRef.value?.updateDic("parentId");
    },
  }
);
const { searchChange, searchReset } = useTableSearch(page, onLoad);
const { selectionChange, selectionList, ids } = useTableSelection();
const { permission } = useTablePermission();
const cudOptions: CudOptions = {
  cRequest: add,
  uRequest: update,
  dRequest: remove,
  tableRequest: onLoad,
  page,
};
const { rowDel, rowSave, rowUpdate } = useTableCUD(cudOptions);

const permissionList = computed(() => ({
  addBtn: validData(permission.value.menu_add, false),
  viewBtn: validData(permission.value.menu_view, false),
  delBtn: validData(permission.value.menu_delete, false),
  editBtn: validData(permission.value.menu_edit, false),
}));

const isAddSon = ref(false); // 标识是否新增子项
const option = reactive({
  searchShow: true,
  searchMenuSpan: 3,
  tip: false,
  // tree: true,
  align: "center",
  border: false,
  index: true,
  selection: true,
  addBtn: true,
  viewBtn: true,
  delBtn: true,
  editBtn: true,
  columnBtn: false,
  refreshBtn: false,
  searchShowBtn: false,
  menuWidth: 240,
  dialogClickModal: false,
  rowKey: "id",
  rowParentKey: "parentId",
  column: [
    {
      label: "菜单名称",
      sortable: true,
      minWidth: 120,
      prop: "name",
      search: true,
      align: "left",
      rules: [
        {
          required: true,
          message: "请输入菜单名称",
          trigger: "blur",
        },
      ],
    },
    {
      label: "路由地址",
      sortable: true,
      minWidth: 120,
      prop: "path",
      align: "left",
      rules: [
        {
          required: true,
          message: "请输入路由地址",
          trigger: "blur",
        },
      ],
    },
    {
      label: "上级菜单",
      prop: "parentId",
      type: "tree",
      dicUrl: "/cupSystemApi/menu/tree",
      dicFormatter: function (res) {
        return res?.data ?? [];
      },
      hide: true,
      checkStrictly: true,
      // parent: true,
      // expandOnClickNode: false,
      props: {
        label: "title",
        value: "id",
      },
      rules: [
        {
          required: false,
          message: "请选择上级菜单",
          trigger: "click",
        },
      ],
    },
    {
      label: "菜单编号",
      sortable: true,
      minWidth: 120,
      prop: "code",
      search: true,
      align: "left",
      rules: [
        {
          required: true,
          message: "请输入菜单编号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "菜单类型",
      prop: "category",
      type: "radio",
      dicData: [
        {
          label: "菜单",
          value: 1,
        },
        {
          label: "按钮",
          value: 2,
        },
      ],
      hide: true,
      rules: [
        {
          required: true,
          message: "请选择菜单类型",
          trigger: "blur",
        },
      ],
    },
    {
      label: "菜单别名",
      sortable: true,
      minWidth: 120,
      prop: "alias",
      align: "left",
      rules: [
        {
          required: true,
          message: "请输入菜单别名",
          trigger: "blur",
        },
      ],
    },
    {
      label: "按钮功能",
      prop: "action",
      type: "radio",
      dicData: [
        {
          label: "工具栏",
          value: 1,
        },
        {
          label: "操作栏",
          value: 2,
        },
        {
          label: "工具操作栏",
          value: 3,
        },
      ],
      hide: true,
      rules: [
        {
          required: true,
          message: "请选择按钮功能",
          trigger: "blur",
        },
      ],
    },
    {
      label: "菜单排序",
      sortable: true,
      minWidth: 120,
      prop: "sort",
      type: "number",
      min: 1,
      max: 9999,
      rules: [
        {
          required: true,
          message: "请输入菜单排序",
          trigger: "blur",
        },
      ],
    },
    {
      label: "显示菜单",
      prop: "showLink",
      type: "radio",
      dicData: [
        {
          label: "否",
          value: 0,
        },
        {
          label: "是",
          value: 1,
        },
      ],
      rules: [
        {
          required: true,
          message: "请选择是否显示菜单",
          trigger: "change",
        },
      ],
      hide: true,
    },
    {
      label: "显示父级",
      prop: "isOpen",
      type: "radio",
      dicData: [
        {
          label: "否",
          value: 0,
        },
        {
          label: "是",
          value: 1,
        },
      ],
      hide: true,
    },
    {
      label: "菜单备注",
      prop: "remark",
      type: "textarea",
      span: 24,
      minRows: 6,
      hide: true,
    },
  ],
});

const beforeOpen = (done, type) => {
  if (["edit", "view"].includes(type)) {
    getMenu(form.value.id).then((res) => {
      form.value = res?.data;
    });
  }
  if (type === "add" && !isAddSon.value) {
    crudRef.value.option.column.forEach((item) => {
      if (item.prop === "parentId") {
        item.value = "";
      }
    });
    crudRef.value.init();
  }
  isAddSon.value = false;
  done();
};

// watch(
//   () => form.value.parentId,
//   (val) => {
//     if (val === "0") {
//       form.parentId = "顶级";
//     }
//   }
// );

const handleAdd = (row) => {
  crudRef.value.option.column.forEach((item) => {
    if (item.prop === "parentId" && isAddSon.value) {
      item.value = row.id;
    }
  });
  crudRef.value.rowAdd();
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning("请选择至少一条数据");
    return;
  }
  ElMessageBox.confirm("确定将选择数据删除?", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page);
      ElMessage({
        type: "success",
        message: "操作成功!",
      });
      crudRef.value.toggleSelection();
    });
};
</script>
